package com.wocai.jrt.orgadmin.product.action;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.vteba.utils.id.ObjectId;
import com.vteba.web.action.GenericAction;
import com.vteba.web.action.JsonBean;
import com.vteba.web.editer.DoubleEditor;
import com.vteba.web.editer.IntEditor;
import com.vteba.web.editer.LongEditor;
import com.vteba.web.editer.StringEditor;
import com.wocai.jrt.orgadmin.message.service.spi.MessageLogService;
import com.wocai.jrt.orgadmin.product.model.Product;
import com.wocai.jrt.orgadmin.product.model.ProductNet;
import com.wocai.jrt.orgadmin.product.service.spi.ProductNetService;
import com.wocai.jrt.orgadmin.product.service.spi.ProductService;
import com.wocai.jrt.orgadmin.utils.UserUtils;

/**
 * 产品净值控制器
 * 
 * @author yinlei
 * @date 2015-8-13 16:43:27
 */
@Controller
@RequestMapping("/productNet")
public class ProductNetAction extends GenericAction<ProductNet> {
	private static final Logger LOGGER = LoggerFactory.getLogger(ProductNetAction.class);

	@Inject
	private ProductNetService productNetServiceImpl;

	@Inject
	private ProductService productServiceImpl;

	@Inject 
	private MessageLogService messageLogServiceImpl;	
	
	@InitBinder
	protected void initBinder(WebDataBinder binder) {
		// 空字符串转换为null
		binder.registerCustomEditor(int.class, new IntEditor());
		binder.registerCustomEditor(long.class, new LongEditor());
		binder.registerCustomEditor(double.class, new DoubleEditor());
		binder.registerCustomEditor(String.class, new StringEditor());
		binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat(
				"yyyy-MM-dd"), true));
	}

	/**
	 * 获得产品净值List，初始化列表页。
	 * 
	 * @param model
	 *            参数
	 * @return 产品净值List
	 */
	@RequestMapping("/net/{productId}")
	public String net(@PathVariable("productId") String productId, Map<String, Object> maps) {
		Product product = productServiceImpl.get(productId);
		maps.put("product", product);
		return "product/net";
	}

	/**
	 * 获得产品净值List，Json格式。
	 * 
	 * @param model
	 *            参数
	 * @return 产品净值List
	 */
	@ResponseBody
	@RequestMapping("/query")
	public Map<String, Object> query(@RequestBody ProductNet model) {
		Map<String, Object> map = new HashMap<String, Object>();

		try {
			LOGGER.info("request product net, param = [{}]", JSON.toJSONString(model));
			int size = productNetServiceImpl.countBy(model);

			if (model.getPageSize() == -1) {
				model.setStart(null);
			}
			
			model.setOrderBy("date desc");
			List<ProductNet> list = productNetServiceImpl.pagedList(model);

			map.put("aaData", list); // 返回的数据
			map.put("iTotalRecords", size); // 总记录数
			map.put("iTotalDisplayRecords", size); // 显示的记录数

		} catch (Exception e) {
			LOGGER.error("request product net error, msg = [{}]", e.getMessage());
		}

		return map;
	}

	/**
	 * 根据Id获得产品净值实体，Json格式。
	 * 
	 * @param id
	 *            参数id
	 * @return 产品净值实体
	 */
	@ResponseBody
	@RequestMapping("/get")
	public ProductNet get(String id) {
		ProductNet model = null;
		try {
			model = productNetServiceImpl.get(id);
		} catch (Exception e) {
			LOGGER.error("get record error, errorMsg=[{}].", e.getMessage());
		}
		return model;
	}

	/**
	 * 跳转到新增页面
	 * 
	 * @return 新增页面逻辑视图
	 */
	@RequestMapping("/add")
	public String add() {
		return "productNet/add";
	}

	/**
	 * 执行实际的新增操作
	 * 
	 * @param model
	 *            要新增的数据
	 * @return 新增页面逻辑视图
	 */
	@ResponseBody
	@RequestMapping("/doAdd")
	public JsonBean doAdd(ProductNet model) {
		JsonBean bean = new JsonBean();
		try {
			Date date = model.getDate();
			Double unitNet = model.getUnitNet();
			if (null == unitNet || null == date) {
				bean.setMessage("param is error");
				return bean;
			}
			
			int count = productNetServiceImpl.countBy(model);
			if (count > 0) {
				bean.setCode(2);
				bean.setMessage("the unit net with date is exist");
				return bean;
			}

			model.setId(ObjectId.get().toString());
			model.setOrgId(UserUtils.getUser().getOrgId());
			int result = productNetServiceImpl.save(model);
			if (result == 1) {
				bean.setMessage(SUCCESS);
				bean.setCode(1);
				LOGGER.info("save record success.");
				//新增净值成功,向投后APP用户推送消息
				messageLogServiceImpl.productNetValueMessage(model);
			} else {
				bean.setMessage(ERROR);
				LOGGER.error("save record error.");
			}
		} catch (Exception e) {
			LOGGER.error("save record error, errorMsg=[{}].", e.getMessage());
			bean.setMessage(ERROR);
		}
		return bean;
	}

	/**
	 * 查看产品净值详情页。
	 * 
	 * @param model
	 *            查询参数，携带ID
	 * @return 产品净值详情页
	 */
	@RequestMapping("/detail")
	public String detail(ProductNet model, Map<String, Object> maps) {
		try {
			model = productNetServiceImpl.get(model.getId());
			maps.put("model", model);// 将model放入视图中，供页面视图使用
		} catch (Exception e) {
			LOGGER.error("query record detail, errorMsg=[{}].", e.getMessage());
			return "common/error";
		}
		return "productNet/detail";
	}

	/**
	 * 跳转到编辑信息页面
	 * 
	 * @param model
	 *            查询参数，携带ID
	 * @return 编辑页面
	 */
	@RequestMapping("/edit")
	public String edit(ProductNet model, Map<String, Object> maps) {
		model = productNetServiceImpl.get(model.getId());
		maps.put("model", model);
		return "productNet/edit";
	}

	/**
	 * 更新产品净值信息
	 * 
	 * @param model
	 *            要更新的产品净值信息，含有ID
	 * @return 操作结果信息
	 */
	@ResponseBody
	@RequestMapping("/update")
	public JsonBean update(ProductNet model) {
		JsonBean bean = new JsonBean();
		try {
			int result = productNetServiceImpl.updateById(model);
			if (result == 1) {
				bean.setMessage(SUCCESS);
				bean.setCode(1);
				LOGGER.info("update record success.");
			} else {
				bean.setMessage(ERROR);
				LOGGER.error("update record error.");
			}
		} catch (Exception e) {
			LOGGER.error("update record error, errorMsg=[{}].", e.getMessage());
			bean.setMessage(ERROR);
		}
		return bean;
	}

	/**
	 * 删除产品净值信息
	 * 
	 * @param id
	 *            要删除的产品净值ID
	 */
	@ResponseBody
	@RequestMapping("/delete")
	public JsonBean delete(String id) {
		JsonBean bean = new JsonBean();
		try {
			int result = productNetServiceImpl.deleteById(id);
			if (result == 1) {
				bean.setMessage(SUCCESS);
				bean.setCode(1);
				LOGGER.info("delete record success, id=[{}].", id);
			} else {
				bean.setMessage(ERROR);
				LOGGER.error("delete record error.");
			}
		} catch (Exception e) {
			LOGGER.error("delete record error, id=[{}], errorMsg=[{}].", id, e.getMessage());
			bean.setMessage(ERROR);
		}
		return bean;
	}
}
